package com.itheima.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.common.entity.PageResult;
import com.itheima.common.entity.QueryPageBean;
import com.itheima.common.utils.AliOssUtil;
import com.itheima.mapper.SetmealMapper;
import com.itheima.pojo.dto.SetmealDTO;
import com.itheima.pojo.entity.Setmeal;
import com.itheima.service.SetmealService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;

@Service
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private AliOssUtil aliOssUtil;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public void addSetmeal(SetmealDTO setmealDTO) {
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO,setmeal);

        String setmealPath=setmeal.getImg();
        SetOperations setOperations = redisTemplate.opsForSet();
        setOperations.add("setmealPath",setmealPath);

        setmealMapper.insertSetmeal(setmeal);
    }

    @Override
    public void editSetmeal(Setmeal setmeal) {
        setmealMapper.updateSetmeal(setmeal);
    }

    @Override
    public Setmeal findByIdSetmeal(String id) {
        return setmealMapper.selectById(Integer.valueOf(id));
    }

    @Override
    public PageResult findPageSetmeal(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        List<Setmeal> list=setmealMapper.selectAll();
        PageInfo<Setmeal> setmealPageInfo = new PageInfo<>(list);
        return new PageResult(setmealPageInfo.getTotal(),setmealPageInfo.getList());
    }

    @Override
    public String uploadSetmeal(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String suffix=originalFilename.substring(originalFilename.lastIndexOf("."));
        String newFileName=System.currentTimeMillis()+suffix;
        String objectName="upload/setmeal/"+newFileName;
        String ObjectPath = aliOssUtil.upload(file.getBytes(), objectName);

        SetOperations setOperations = redisTemplate.opsForSet();
        setOperations.add("uploadSetmeal",ObjectPath);

        return ObjectPath;
    }

    @Override
    public List<Setmeal> getSetmeal() {
        List<Setmeal> list=setmealMapper.getSetmeal();
        return list;
    }

    @Override
    public Setmeal findById(String id) {
        Setmeal setmeal=setmealMapper.selectById(Integer.valueOf(id));
        return setmeal;
    }

}
